<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>欢迎登录</h2>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password clearable @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row :gutter="8" style="width: 100%">
            <el-col :span="16">
              <el-input v-model="loginForm.captcha" placeholder="请输入验证码" clearable />
            </el-col>
            <el-col :span="8" class="captcha-img-col">
              <img :src="loginCaptchaImg" class="captcha-img" @click="refreshLoginCaptcha" title="点击刷新验证码" alt="验证码" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        <p>还没有账号？<el-link type="primary" :underline="false" @click="registerDialogVisible = true">立即注册</el-link></p>
      </div>
    </div>
    <!-- 注册对话框 -->
    <el-dialog v-model="registerDialogVisible" title="用户注册" width="400px" :close-on-click-modal="false">
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
        size="large"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password clearable />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="8" style="width: 100%">
            <el-col :span="16">
              <el-input v-model="registerForm.captcha" placeholder="请输入验证码" clearable />
            </el-col>
            <el-col :span="8" class="captcha-img-col">
              <img :src="registerCaptchaImg" class="captcha-img" @click="refreshRegisterCaptcha" title="点击刷新验证码" alt="验证码" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="registerLoading" @click="handleRegister">注册</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import http from '@/api/http'
import { getCaptcha, verifyCaptcha } from '@/api/captcha'

const router = useRouter()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const loginCaptchaImg = ref('')
const loginCaptchaUuid = ref('')
const refreshLoginCaptcha = async () => {
  const res = await getCaptcha()
  loginCaptchaImg.value = res.data.img
  loginCaptchaUuid.value = res.data.uuid
}
onMounted(refreshLoginCaptcha)

const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 6, message: '用户名长度为2-6个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  try {
    await loginFormRef.value.validate()
    // 先校验验证码
    const verifyRes = await verifyCaptcha({ uuid: loginCaptchaUuid.value, code: loginForm.captcha })
    if (verifyRes.code !== 200) {
      ElMessage.error(verifyRes.msg || '验证码错误')
      refreshLoginCaptcha()
      return
    }
    loading.value = true
    await http.post('/login', {
      username: loginForm.username,
      password: loginForm.password
    })
    ElMessage.success('登录成功！')
    loading.value = false
    router.push('/main')
  } catch (error: any) {
    loading.value = false
    ElMessage.error(error?.msg || '登录失败')
    refreshLoginCaptcha()
  }
}

// 注册相关
const registerDialogVisible = ref(false)
const registerFormRef = ref<FormInstance>()
const registerLoading = ref(false)
const registerForm = reactive({
  username: '',
  password: '',
  captcha: ''
})
const registerCaptchaImg = ref('')
const registerCaptchaUuid = ref('')
const refreshRegisterCaptcha = async () => {
  const res = await getCaptcha()
  registerCaptchaImg.value = res.img
  registerCaptchaUuid.value = res.uuid
}
onMounted(refreshRegisterCaptcha)
const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 6, message: '用户名长度为2-6个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}
const handleRegister = async () => {
  if (!registerFormRef.value) return
  try {
    await registerFormRef.value.validate()
    // 先校验验证码
    const verifyRes = await verifyCaptcha({ uuid: registerCaptchaUuid.value, code: registerForm.captcha })
    if (verifyRes.code !== 200) {
      ElMessage.error(verifyRes.msg || '验证码错误')
      refreshRegisterCaptcha()
      return
    }
    registerLoading.value = true
    await http.post('/register', {
      username: registerForm.username,
      password: registerForm.password
    })
    ElMessage.success('注册成功，请登录！')
    registerLoading.value = false
    registerDialogVisible.value = false
  } catch (error: any) {
    registerLoading.value = false
    ElMessage.error(error?.msg || '注册失败')
    refreshRegisterCaptcha()
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-box {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.97);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px 30px 20px 30px;
  position: relative;
}
.login-header {
  text-align: center;
  margin-bottom: 30px;
}
.login-header h2 {
  color: #303133;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
}
.login-form {
  margin-bottom: 10px;
}
.captcha-img-col {
  display: flex;
  align-items: center;
  height: 40px;
}
.captcha-img {
  width: 100%;
  height: 40px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 6px;
  border: 1px solid #eee;
  background: #fff;
}
.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}
.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}
.login-footer {
  text-align: center;
  margin-top: 20px;
}
.login-footer p {
  color: #606266;
  font-size: 14px;
  margin: 0;
}
</style> 